package com.moter.demo01.requirements;

import java.sql.*;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

public class Demo2 {
    private static volatile int connections = 0;
    public static String url ="jdbc:mysql://localhost:3306/vue?characterEncoding=UTF-8&serverTimezone=UTC";
    public static String username = "root";
    public static String password = "hhxxttxs123";
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            Demo2 demo2 = new Demo2();
            int finalI = i;
            new Thread(() -> {
                try {
                    TimeUnit.MICROSECONDS.sleep(finalI*100);
                    demo2.addConnection();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }catch (RuntimeException e){
                    System.out.println(e.getMessage());
                }
            }).start();
        }
    }

    public void addConnection() {
        synchronized (Demo2.class) {
            if (connections >= 10) {
                throw new RuntimeException("超过最大连接数");
            } else {
                connections++;

            }
        }
        doBusiness(connect(url,username,password));
    }

    /**
     * 获取链接
     * @param url
     * @param username
     * @param password
     * @return
     */
    public Connection connect(String url,String username,String password){
        Connection connection = null;
        try {
            //导入驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url,username,password);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
        return connection;
    }

    /**
     * 业务逻辑
     * @param connection
     */
    public void doBusiness(Connection connection){
        if(connection==null){
            throw new RuntimeException("No Such Connection Exception");
        }
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if(resultSet!=null)
                    resultSet.close();
                if(preparedStatement!=null)
                    preparedStatement.close();
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            synchronized (Demo2.class){
                connections--;
            }
        }
    }
}
